package ru.cybertek.dao.impl.jdbc;

import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import ru.cybertek.domain.Person;

/**
 * @author Dmitry Demyankov
 * @version $Revision: 10 $
 * 
 *          (C) Copyright 2009 CyberTek Ltd. All rights reserved.
 */
public class AddPersonSqlQuery extends SqlUpdate
{
    public static final String INSERT_PERSON_SQL_QUERY = "INSERT INTO person SET first_name = :firstName,"
        + " middle_name = :middleName, last_name = :lastName";

    public static final String PERSON_FIRST_NAME_PARAMETER = "firstName";

    public static final String PERSON_MIDDLE_NAME_PARAMETER = "middleName";

    public static final String PERSON_LAST_NAME_PARAMETER = "lastName";

    /**
     * @param dataSource
     */
    public AddPersonSqlQuery(DataSource dataSource)
    {
        setDataSource(dataSource);
        setSql(INSERT_PERSON_SQL_QUERY);
        declareParameter(new SqlParameter(Types.VARCHAR));
        declareParameter(new SqlParameter(Types.VARCHAR));
        declareParameter(new SqlParameter(Types.VARCHAR));
        compile();
    }

    /**
     * @param person
     * @throws DataAccessException
     */
    public void update(Person person) throws DataAccessException
    {
        Map<String, Object> namedParameters = new HashMap<String, Object>(3);
        namedParameters.put(PERSON_FIRST_NAME_PARAMETER, person.getFirstName());
        namedParameters.put(PERSON_MIDDLE_NAME_PARAMETER, person
            .getMiddleName());
        namedParameters.put(PERSON_LAST_NAME_PARAMETER, person.getLastName());

        KeyHolder keyHolder = new GeneratedKeyHolder();
        super.updateByNamedParam(namedParameters, keyHolder);

        person.setId(keyHolder.getKey().intValue());
    }
}
